const { defineConfig } = require('@vue/cli-service')
const resolve = require('path').resolve
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
const isProduction = process.env.NODE_ENV === 'production'

module.exports = defineConfig({
  publicPath: isProduction ? '/admin/' : '/',
  productionSourceMap: false,
  transpileDependencies: true,
  css: {
    extract: false,
  },
  devServer: {
    proxy: {
      '/api': {
        target: 'http://121.43.57.185:8089',
        pathRewrite: { '^api': '' }
      }
    }
  },
  configureWebpack: config => {
    const plugins = config.plugins
    plugins.push(new NodePolyfillPlugin())
  },
  chainWebpack: config => {
    config.when(!isProduction, config => config.devtool('eval'))
    config.module.rule('svg')
      .exclude.add(resolve('src/icons/svg'))
      .end()

    config.plugin('html')
      .tap(args => {
        args[0].title = '企业能耗管理系统'
        return args
      })

    config.module.rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons/svg'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
      .use('svgo-loader')
      .loader('svgo-loader')
      .options({
        plugins: [{
          name: 'removeAttrs',
          params: {
            attrs: 'fill'
          }
        }]
      })
      .end()

    // Optimization
    // https://webpack.docschina.org/plugins/split-chunks-plugin/#optimizationsplitchunks
    if (isProduction) {
      config.optimization.splitChunks({
        chunks: 'all',
        minChunks: 1,
        cacheGroups: {
          common: {
            name: 'chunk-common',
            priority: 5,
          },
          vendors: {
            name: 'chunk-vendors',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial'
          },
          elementUi: {
            name: 'chunk-element-ui',
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/,
            priority: 20,
          },
        }
      })
    }
  }
})
